from lib.re_config import CONFIG
import pymysql

# MysqlClient1 与 MysqlClient是等价效果
class MysqlClient(object):
    # 初始化参数
    def __init__(self,host=None,port=None,user=None,password=None,database=None):
        # 三目运算符写法
        # 这样设置的好处在于下面 connect 传入参数时不需要填写过长过多的数据，仅仅只需 **self.params 便可以完成数据的解包
        self.params = {
            'host' : CONFIG['database']['host'] if host is None else host,
            'port' : int(CONFIG['database']['port']) if port is None else port,
            'user' : CONFIG['database']['user'] if user is None else user,
            'password' : CONFIG['database']['password'] if password is None else password,
            'database' : CONFIG['database']['database'] if database is None else database
        }
    # MysqlClient1
    # 定义查找功能
    def select(self,sql):
        # ** 两个星号的作用是对字典 self.params 进行解包，并以 A=B 的形式获取字典中的数据
        with pymysql.connect(**self.params) as py_connect:
            with py_connect.cursor() as py_cursor:
                return py_cursor.execute(sql)

    def client(self,sql_list:list):
        with pymysql.connect(**self.params) as py_connect:
            with py_connect.cursor() as py_cursor:
                try:
                    for sql in sql_list:
                        py_cursor.execute(sql)
                        print(sql)
                except Exception:
                    py_connect.rollback()
                    return False
                else:
                    py_connect.commit()
                    return True

class MysqlClient1(object):
    # 初始化参数
    def __init__(self,host=None,port=None,user=None,password=None,database=None):
        # 三目运算符写法
        self.host = CONFIG['database']['host'] if host is None else host
        self.port = int(CONFIG['database']['port']) if port is None else port
        self.user = CONFIG['database']['user'] if user is None else user
        self.password = CONFIG['database']['password'] if password is None else password
        self.database = CONFIG['database']['database'] if database is None else database

    # 定义查找功能
    def select(self,sql):
        with pymysql.connect(host=self.host,port=self.port,user=self.user,password=self.password,database=self.database) as py_connect:
            with py_connect.cursor() as py_cursor:
                return py_cursor.execute(sql)

    def client(self,sql_list:list):
        with pymysql.connect(host=self.host,port=self.port,user=self.user,password=self.password,database=self.database) as py_connect:
            with py_connect.cursor() as py_cursor:
                try:
                    for sql in sql_list:
                        py_cursor.execute(sql)
                        print(sql)
                except Exception:
                    py_connect.rollback()
                    return False
                else:
                    py_connect.commit()
                    return True